package gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import entities.CoSigner;
import entities.FinancialInfo;

/**
 * panel for cosigner application
 * 
 * @author gke703
 * */
public class CosignerPanel extends JPanel {

	/** panel for cosigner personal info */
	protected PersonalInfoPanel lpanel;

	/** panel for cosigner financial info */
	protected FinancialInfoPanel rpanel;

	/** frame panel is mounted in */
	private JFrame myFrame;

	/** greater application that cosigner application is a part of */
	private LoanInfoPanel appPanel;

	/**
	 * panel for cosigner loan application
	 * 
	 * @param frame
	 *            JFrame panel is mounted in
	 * @param panel
	 *            LoanInfoPanel which cosigner will be connected with
	 */
	public CosignerPanel(JFrame frame, LoanInfoPanel panel) {

		myFrame = frame;
		appPanel = panel;

		appPanel.appCosigner = null;
		setLayout(new GridLayout(2, 2));

		lpanel = new PersonalInfoPanel();
		add(lpanel);

		rpanel = new FinancialInfoPanel();
		add(rpanel);

		JPanel p = new JPanel();
		JButton bu = new JButton("Set Cosigner");
		JButton bu2 = new JButton("Cancel");
		p.add(bu);
		p.add(bu2);
		add(p);

		// set cancel button to close frame
		bu2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				myFrame.setVisible(false);
			}
		});

		bu.addActionListener(new ApplyListener());
	}

	/**
	 * error checks form extensively allows creation of loan cosigner if
	 * possible
	 * 
	 * @author gke703
	 */
	private class ApplyListener implements ActionListener {

		/**
		 * evaluates whether form was filled out properly informs user if it was
		 * not, creates cosigner for application if it was
		 * */
		@Override
		public void actionPerformed(ActionEvent event) {
			boolean isValid = true; // manage if input to application form is
			// valid or not
			String errorString = ""; // error message if needed

			String cosignerName = lpanel.nameField.getValueAsString();
			// check if input is alphanumeric
			String remainingJunk = cosignerName.replaceAll("[a-zA-Z ]", "");
			if (remainingJunk.length() > 0 || cosignerName.length() == 0) {
				errorString += "Invalid input for Name\n";
				isValid = false;
			}

			// get birthdate info in format MM/dd/yyyy
			String cosignerBirthdate = lpanel.birthdateField.getValueAsString();
			remainingJunk = cosignerBirthdate.replaceAll("[0-9/]", "");
			// check for proper format
			boolean isValidDate = cosignerBirthdate
					.matches("[0-1][0-9]/[0-3][0-9]/[0-2][90][0-9][0-9]");
			if (!isValidDate || remainingJunk.length() > 0) {
				errorString += "Invalid input for birthdate, should be mm/dd/yyyy\n";
				isValid = false;
			}

			String cosignerAddress = lpanel.addressField.getValueAsString();
			remainingJunk = cosignerAddress.replaceAll("[a-zA-Z.0-9 ]", "");
			if (remainingJunk.length() > 0 || cosignerAddress.length() == 0) {
				errorString += "Invalid input for Address\n";
				isValid = false;
			}

			String cosignerPhone = lpanel.phonenumberField.getValueAsString();
			remainingJunk = cosignerPhone.replaceAll("[0-9 ()-]", "");
			if (remainingJunk.length() > 0 || cosignerPhone.length() == 0) {
				errorString += "Invalid input for Phone Number\n";
				isValid = false;
			}

			String cosignerEmail = lpanel.emailField.getValueAsString();
			remainingJunk = cosignerEmail.replaceAll("[a-zA-Z0-9.@()-]", "");
			if (remainingJunk.length() > 0 || cosignerEmail.length() == 0) {
				errorString += "Invalid input for e-mail\n";
				isValid = false;
			}

			float cosignerPersonalIncome = 0;
			try {
				cosignerPersonalIncome = rpanel.personalField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerPersonalIncome = 0;
			}

			if (cosignerPersonalIncome < 0) {
				isValid = false;
				errorString += "Personal Income must be positive\n";
			}

			float cosignerHouseholdIncome = 0;
			try {
				cosignerHouseholdIncome = rpanel.householdField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerHouseholdIncome = 0;
			}

			if (cosignerHouseholdIncome < 0) {
				isValid = false;
				errorString += "Household Income must be positive\n";
			}

			float cosignerTaxIncome = 0;
			try {
				cosignerTaxIncome = rpanel.taxField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerTaxIncome = 0;
			}

			if (cosignerTaxIncome < 0) {
				isValid = false;
				errorString += "Taxable Income must be positive\n";
			}

			float cosignerChildSupport = 0;
			try {
				cosignerChildSupport = rpanel.childField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerChildSupport = 0;
			}

			if (cosignerChildSupport < 0) {
				isValid = false;
				errorString += "Child Support must be positive\n";
			}

			float cosignerScholarship = 0;
			try {
				cosignerScholarship = rpanel.scholarField.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerScholarship = 0;
			}

			if (cosignerScholarship < 0) {
				isValid = false;
				errorString += "Scholarship must be positive\n";
			}

			float cosignerMonthlyExpenses = 0;
			try {
				cosignerMonthlyExpenses = rpanel.monthlyExpensesField
						.getValueAsFloat();
			} catch (NumberFormatException e) {
				isValid = false;
				errorString += e.getMessage() + "\n";
				cosignerMonthlyExpenses = 0;
			}

			if (cosignerMonthlyExpenses < 0) {
				isValid = false;
				errorString += "Monthly Expenses must be positive\n";
			}

			if (isValid) {
				CoSigner myCo = new CoSigner(-1);
				myCo.setAddress(cosignerAddress);
				myCo.setBirthdate(cosignerBirthdate);
				myCo.setEmail(cosignerEmail);
				myCo.setName(cosignerName);
				myCo.setPhoneNumber(cosignerPhone);

				FinancialInfo myF = new FinancialInfo();
				myF.setChildSupport(cosignerChildSupport);
				myF.setHouseholdIncome(cosignerHouseholdIncome);
				myF.setPersonalIncome(cosignerPersonalIncome);
				myF.setScholarship(cosignerScholarship);
				myF.setTaxableEarnings(cosignerTaxIncome);
				myF.setTaxableEarnings(cosignerMonthlyExpenses);

				// sets cosigner as an attribute of main loan application panel
				// for proper access
				myCo.setFinancialInfo(myF);
				appPanel.appCosigner = myCo;
				myFrame.setVisible(false);
			} else {
				JOptionPane.showMessageDialog(myFrame, errorString);
			}

		}
	}

	private static final long serialVersionUID = 1L;

}
